#!/usr/bin/python
# -*- coding: utf-8 -*-
from datetime import datetime

from bs4 import BeautifulSoup, BeautifulStoneSoup
import imgkit
import sys
import os
script_dir = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(script_dir,'/Core'))
import http_rest


def GetDetailedContInfo(contnumber):
    options = {'encoding': "UTF-8", "quality": "80", "width": "1124"}
    path_wkthmltoimage = r'/usr/bin/wkhtmltoimage'
    config = imgkit.config(wkhtmltoimage=path_wkthmltoimage)
    css = ['/opt/css/bootstrap.css']
    billing = http_rest.send_soap_req('billing')
    response = billing.service.GetDetailedContInfo(contnumber)
    y = BeautifulSoup(response, features="lxml")

    if y.data.rescode:
        return False
    status = y.data.status.text if y.data.status else ''
    transportin = y.data.transportin.text if y.data.transportin else ''
    datein = y.data.datein.text if y.data.datein else ''
    dateout = y.data.dateout.text if y.data.dateout else ''
    vesselid = y.data.vesselid.text if y.data.vesselid else ''
    vesselname = y.data.vesselname.text if y.data.vesselname else ''
    contsize = y.data.contsize.text if y.data.contsize else ''
    conttype = y.data.conttype.text if y.data.conttype else ''
    contowner = y.data.contowner.text if y.data.contowner else ''
    expediter = y.data.expediter.text if y.data.expediter else ''
    expediterinn = y.data.expediterinn.text if y.data.expediterinn else ''
    customsway = y.data.customsway.text if y.data.customsway else ''
    resolution = 'Нет'
    customblock = 'Нет'
    release = 'Нет'
    now = datetime.now()
    html_text = """
    <html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  </head>
  <body style="width:1114px;padding-top:15px;">
  <div class="container-fluid">
  <div class="row justify-content-md-center">
   <div class="col-12">
  <table class='table table-striped table-bordered table-condensed'> 
    			   <thead>
    			<tr class='table-info'><th colspan="6">Создано @TMRP_bot, Актуально на: """ + now.strftime("%H:%M:%S %d.%m.%Y") + """</th></tr>
    				<tr class='table-success'>
    					<th>Номер</th>
    					<th width="20px">Размер</th>
    					<th width="20px">Вид</th>
    					<th>Владелец</th>
    					<th>Экспедитор</th>
    					<th>ИНН</th>
    				</tr>
    			</thead>
    			<tdoby>
    				<tr align="center">
    				<td>""" + contnumber + """</td>
    				<td>""" + contsize + """</td>
    				<td>""" + conttype + """</td>
    				<td>""" + contowner + """</td>
    				<td>""" + expediter + """</td>
    				<td>""" + expediterinn + """</td>
    				</tr>
    				</tbody>
    				</table>"""
    html_text += """
    </div>
    </div>
    		<div class="row justify-content-md-center">
    		 <div class="col-12">
    		<table  class='table table-striped table-bordered table-condensed'>
    	<tr class='table-success'>
    	<th>Статус</th>
    	<th>способ ввоза</th>
    	<th>Дата прихода</th>
    	<th>Дата ухода</th>
    	<th>Рейс</th>
    	<th>Судно</th>
    	</tr>
    	<tr align="center">
    	<td>""" + status + """</td>	
    	<td>""" + transportin + """</td>
    	<td>""" + datein + """</td>
    	<td>""" + dateout + """</td>
    	<td>""" + vesselid + """</td>
    	<td>""" + vesselname + """</td>
    </table>
    </div></div>
       """



    if status != 'На подходе':
        if customsway =='Импорт':
            custom_sub_text = """<tr class='table-success'>
              			<th>Коносамент</th>
              			<th width="76px">Дата коносамент</th>
              			<th>ДО1</th>
              			<th>ДТ</th>
              		</tr>"""
            if y.data.resolution.text == 'Да' and y.data.customsblock.text == '' and y.data.release.text != '':
                resolution = 'Да'
            customblock = y.data.customsblock.text
            if y.data.release.text != '':
                release = 'Да'
            custom_doc = list(y.data.customdoc.children)
            custom_count = len(list(y.data.customdoc.children))

            for i in range(1, custom_count, 2):
                customdoc_substring = list(custom_doc[i])
                custom_sub_text += '<tr align="center">'
                custom_sub_text += "<td>" + customdoc_substring[1].text + "</td>"
                custom_sub_text += "<td>" + customdoc_substring[3].text + "</td>"
                custom_sub_text += "<td>" + customdoc_substring[5].text + "</td>"
                custom_sub_text += "<td>" + customdoc_substring[7].text + "</td>"
                custom_sub_text += """</tr>"""
            custom_sub_text += """
                </table >
                </div>
                </div>
                <div class="row justify-content-md-center">
                 <div class="col-12">
                <table  class="table table-striped table-bordered table-condensed">
                <tr class="table-success">
                    					<th width="32px">ИМО</th>
                    					<th width="32px">Температура</th>
                    					<th>Пломба коносамент</th>
                    					<th>Пломба факт</th>
                    					<th>Тамож. блок</th>
                    					<th>Транзит</th>
                    					<th>Разнарядка</th>
                    					<th>Релиз</th>
                    					<th>Разреш. на вывоз</th>
                    				</tr>
                    				<tr align='center'>
                    				<td>""" + y.data.classdngr.text + """</td>
                    				<td>""" + y.data.temperature.text + """</td>
                    				<td>""" + y.data.sealsconosament.text + """</td>
                    				<td>""" + y.data.seals.text + """</td>
                    				<td>""" + customblock + """</td>
                    				<td>""" + y.data.transit.text + """</td>
                    				<td>""" + resolution + """</td>
                    				<td>""" + release + """</td>
                    				<td>""" + resolution + """</td>
                    				</tr>
                """


        else:# Экспорт и дэпо
            custom_sub_text = """
					<tr class='table-success'>
					<th width='32px'>IMO</th>
					<th width='32px'>Температура</th>
						<th>Пломба факт</th>
						<th>Букинг</th>
						<th>Договор хранения</th>
						<th>№ ПСО</th>
					</tr>
					<tr align='center'>
					<td>""" + (y.data.classdngr.text if y.data.classdngr else '') +"""</td>
					<td>""" + (y.data.temperature.text if y.data.temperature else '') +"""</td>
					<td>""" + (y.data.seals.text if y.data.seals else '') +"""</td>
					<td>""" + (y.data.booking.text if y.data.booking else '') +"""</td>
					<td>""" + (y.data.dgstorage['dgnumber'] if y.data.dgstorage else '')+"""</td>
					<td>""" + (y.data.psonumber.text if y.data.psonumber else '') +"""</td>
					</tr>"""
        if y.data.operationcomplete:
            operation_list = list(y.data.operationcomplete.children)
            incomplete = len(operation_list)
        else:
            operation_list = []
            incomplete = len(operation_list)
        operation_list_text = ''
        for i in range(1, len(operation_list), 2):
            operation_list_substring = list(operation_list[i])
            operation_list_text += '<tr align="center">'
            opdate = opdatecancel = optype1 = optype2 = status = datepalan = ''
            for j in range(1, len(operation_list_substring), 2):
                if operation_list_substring[j].name == 'opdate':
                    opdate = operation_list_substring[j].contents[0]
                elif operation_list_substring[j].name == 'opdatecancel':
                    opdatecancel = operation_list_substring[j].contents[0]
                elif operation_list_substring[j].name == 'optype1':
                    optype1 = operation_list_substring[j].contents[0]
                elif operation_list_substring[j].name == 'optype2':
                    optype2 =(operation_list_substring[j].contents[0] if operation_list_substring[j].contents else '')
                elif operation_list_substring[j].name == 'status':
                    status = operation_list_substring[j].contents[0]
            operation_list_text += "<td>" + opdate + "</td>"
            operation_list_text += "<td>" + optype1 + "</td>"
            operation_list_text += "<td>" + optype2 + "</td>"
            operation_list_text += "<td>" + datepalan + "</td>"
            operation_list_text += "<td>" + opdatecancel + "</td>"
            operation_list_text += "<td>" + status + "</td>"
            operation_list_text += "</tr>"

        if y.data.operationinprocess:
            operation_list = list(y.data.operationinprocess.children)
            inprogress = len(operation_list)
        else:
            operation_list = []
            inprogress = len(operation_list)
        for i in range(1, len(operation_list), 2):
            operation_list_substring = list(operation_list[i])
            operation_list_text += '<tr align="center">'
            opdate = opdatecancel = optype1 = optype2 = status = opdateplan = ''
            for j in range(1, len(operation_list_substring), 2):
                if operation_list_substring[j].name == 'opdate':
                    opdate = operation_list_substring[j].contents[0]
                elif operation_list_substring[j].name == 'opdatecancel':
                    opdatecancel = operation_list_substring[j].contents[0]
                elif operation_list_substring[j].name == 'optype1':
                    optype1 = operation_list_substring[j].contents[0]
                elif operation_list_substring[j].name == 'optype2':
                    optype2 = (operation_list_substring[j].contents[0] if operation_list_substring[j].contents else '')
                elif operation_list_substring[j].name == 'status':
                    status = operation_list_substring[j].contents[0]
                elif operation_list_substring[j].name == 'opdateplan':
                    opdateplan = operation_list_substring[j].contents[0]
            operation_list_text += "<td>" + opdate + "</td>"

            operation_list_text += "<td>" + optype1 + "</td>"
            operation_list_text += "<td>" + optype2 + "</td>"
            operation_list_text += "<td>" + opdateplan + "</td>"
            operation_list_text += "<td>" + opdatecancel + "</td>"
            operation_list_text += "<td>" + status + "</td>"
            operation_list_text += "</tr>"

        html_text += """
        <div class="row justify-content-md-center">
         <div class="col-12">
        <table  class="table table-striped table-bordered table-condensed">
                        				""" + custom_sub_text + """
                        			</table >
                        			</div>
                        			</div>
                        			"""
        if incomplete + inprogress > 0:
                html_text += """
               
                <div class="row justify-content-md-center">
                <div class="col-12">
            	<table class="table table-striped table-bordered table-condensed">
            			<tr class="table-info"><th colspan="6">Технологические операции (Досмотр/ИДК/Взвешивание)</th></tr>
            			<tr class="table-success">
            				<th width ="110px">Дата Создания</th>
            				<th>Вид операции</th>
            				<th>Тип Операции</th>
            				<th width ="110px">Дата План</th>
            				<th width ="110px">Дата проведения</th>
            				<th>статус</th>
            			</tr>
            			""" + operation_list_text + """

            	</table>	
            	</div>
            	</div>				
            	"""
        else:
            html_text += """
            <div class="row">
            <div class="col-12">
            	<table class="table table-striped table-bordered table-condensed">
            			<tr class="table-info"><th colspan="6">Технологические операции (Досмотр/ИДК/Взвешивание) не проводились!</th></tr>
            	</table>
            	</div>
            	</div>
            	"""
        uktwslist = http_rest.send_soap_req('uktwslist')
        response = uktwslist.service.ContHistory(contnumber)
        y = BeautifulStoneSoup(response, features="xml")
        ContDetails = y.findAll('ContDetails')
        count_d = len(ContDetails)
        cont_d_text=''
        for i in range(count_d):
            TransportIn = 'Импорт' if ContDetails[i].TransportIn.text == 'Морской' else 'Экспорт'
            cont_d_text += '<tr align="center">'
            cont_d_text += '<td>' + ContDetails[i].Arrival.text + '</td>'
            cont_d_text += '<td>' + (ContDetails[i].DocumentU.text if TransportIn == 'Импорт' else '') + '</td>'
            cont_d_text += '<td>' + ContDetails[i].DocumentUKolvo.text + '</td>'
            cont_d_text += '<td>' + ContDetails[i].DocumentUBrutto.text + '</td>'
            cont_d_text += '<td>' + ContDetails[i].TransportIn.text + '</td>'
            cont_d_text += '<td>' + ContDetails[i].Departure.text + '</td>'
            cont_d_text += '<td>' + ContDetails[i].TransportOut.text + '</td>'
            cont_d_text += '<td>' + ('Да' if ContDetails[i].Empty.text == 'False' else 'Нет') + '</td>'
            cont_d_text += '<td>' + (ContDetails[i].Hazardous.text if ContDetails[i].Hazardous else '') + '</td>'
            cont_d_text += '<td>' + (ContDetails[i].Temp.text if ContDetails[i].Temp else '') + '</td>'
            cont_d_text += '<td>' + (ContDetails[i].Documents.text if TransportIn == 'Экспорт' else '') + '</td>'
            cont_d_text += '<td>' + (ContDetails[i].Documents.text if TransportIn == 'Импорт' else '') + '</td>'
        html_text +="""
        <div class="row justify-content-md-center">
        <div class="col-12">
			<table class="table table-striped table-bordered">
			<tr class="table-info"><th colspan="12">Данные о движениях контейнера за последние 3 месяца</th></tr>
			<tr class="table-success">
			    <th>Дата прихода</th>
                <th>ДУ</th>
				<th>Кол-во</th>
				<th>Вес</th>
				<th>Приход</th>
				<th>Дата ухода</th>
				<th>Уход</th>
				<th>Груж.</th>
				<th>IMO</th>
				<th>Темп.</th>
				<th>Букинг</th>
				<th>Коносамент(ы)</th>
			</tr>
			""" + cont_d_text + """
		</table>
		</div>
		</div>
        </div>
		</body>
		</html>"""
    else: # контейнер на подходе другой информации выводить не нужно
        pass
    imgkit.from_string(html_text, 'out.jpg', config=config, options=options,css=css)
    return True
#GetDetailedContInfo('BMOU9657195')